package com.example.springbootdemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RpcService rpcServiceImpl;

    // 用于死锁的两个对象锁
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    @Override
    public String getUser() {
        // 线程1获取lock1，然后尝试获取lock2
        synchronized (lock1) {
            System.out.println("getUser: 获得lock1");

            try {
                Thread.sleep(100); // 给另一个线程获取锁的机会
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            synchronized (lock2) {
                System.out.println("getUser: 获得lock2");
                rpcServiceImpl.rpc();
                rpc2();
            }
        }
        return "wandys";
    }

    public void rpc2() {
        // 线程2获取lock2，然后尝试获取lock1（死锁）
        new Thread(() -> {
            synchronized (lock2) {
                System.out.println("rpc2: 获得lock2");

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

                synchronized (lock1) {
                    System.out.println("rpc2: 获得lock1");
                    rpcServiceImpl.rpc();
                }
            }
        }).start();
    }
}
